package cn.wolfcode.shop.web.frontend;

import cn.wolfcode.shop.alipay.AlipayProperties;
import cn.wolfcode.shop.common.BusinessException;
import cn.wolfcode.shop.domain.OrderInfo;
import cn.wolfcode.shop.service.IOrderInfoService;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

@RestController
public class PayController {

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private AlipayProperties alipayProperties;

    @Autowired
    private IOrderInfoService orderInfoService;

    @RequestMapping("pay")
    public void alipay(String orderNo, HttpServletResponse response)throws Exception{
        OrderInfo orderInfo = orderInfoService.find(orderNo);
        if (orderInfo == null){
            response.sendRedirect("http://localhost/50x.html");
            return;
        }
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());//同步调用地址
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());//异步调用地址

        // 商户订单号，商户网站订单系统唯一订单号，必填
        String out_trade_no = orderInfo.getOrderNo();
        // 付款金额，必填
        String total_amount = orderInfo.getSeckillPrice() + "";
        // 订单名称，必填
        String subject = orderInfo.getGoodName();
        // 商品描述，可空
        String body = "秒杀商品:"+orderInfo.getGoodName();
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // 请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        // 输出
        out.print(result);
    }

    @RequestMapping("/return_url")
    public void returnUrl(@RequestParam Map<String,String> params, HttpServletResponse response)throws Exception{
        System.out.println("同步通知...");
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), alipayProperties.getSignType());
        if (signVerified){
            // 商品订单号
            String out_trade_no = params.get("out_trade_no");
            response.sendRedirect("http://localhost/order_detail.html?orderNo="+out_trade_no);
            return;
        }
        response.sendRedirect("http://localhost/50x.html");
    }

    @RequestMapping("/notify_url")
    public String notifyUrl(@RequestParam Map<String,String> params)throws Exception{
        System.out.println("异步通知...");
        boolean signVerified = AlipaySignature.rsaCheckV1(params,alipayProperties.getAlipayPublicKey(),alipayProperties.getCharset(),alipayProperties.getSignType());
        if (signVerified){
            // 商品订单号
            String out_trade_no = params.get("out_trade_no");
            // 交易状态
            String trade_status = params.get("trade_status");
            if (trade_status.equals("TRADE_FINISHED")){

            }else if (trade_status.equals("TRADE_SUCCESS")){
                // 支付完成
                // 幂等性
                try {
                    orderInfoService.updateOrder(out_trade_no,OrderInfo.STATUS_ACCOUNT_PAID);
                }catch (BusinessException e){
                    e.printStackTrace();
                    //把这个消息放入到mq,监听器监听到消息,给后果管理人员/客服发送消息,客服审核之后,实现订单退款.(调用支付宝的退款)
                }
            }
            return "success";
        }else {
            return "fail";
        }
    }

}
